/*
 * Created on 07.05.2003
 * Local Projects Database
 * (c) 2003 by eRomania Gateway Association
 */
package ro.gateway.aida.struts.action;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ro.gateway.aida.db.DBWrapper;
import ro.gateway.aida.obj.db.LanguageDB;
import ro.gateway.aida.struts.MultiTilesAction;
import ro.gateway.aida.struts.form.TrnHarvestLocationForm;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.usr.User;
import ro.gateway.aida.usr.UserUtils;
import ro.gateway.aida.utils.LocalisedList;
import ro.gateway.aida.utils.Utils;
import ro.ro_gateway.schemas.lpdte_013.ObjectFactory;
import ro.ro_gateway.schemas.lpdte_013.Translations;
import ro.ro_gateway.schemas.lpdte_013.Trn;
import ro.xblue.translator.TransItem;
import ro.xblue.translator.TranslatorDBAccessor;
import ro.xblue.translator.TranslatorUtils;
import ro.xblue.translator.TrnHarvestLocation;
import ro.xblue.translator.TrnHarvestLocationDB;
public class TranslatorExchangeAction extends MultiTilesAction {
	public static SimpleDateFormat sdt = new SimpleDateFormat(
			"dd:MMM:yyyy:HH:mm:ss");
	public ActionForward modePrepare(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (request.getParameter("publish") == null) {
			Arbiter ar = Arbiter.getManager(token);
			User user = UserUtils.getLogged(request, response);
			HttpSession session = request.getSession();
			if (user == null)
				return mapping.findForward("plslogin");
			if (!ar.canDo(request, Perms.ADMIN_TOOLS)) {
				session.invalidate();
				return mapping.findForward("norights");
			}
			String lang = TranslatorUtils.getCurrentLanguage(request, sc)
					.getLanguage();
			LocalisedList langs = (LocalisedList) Utils.getLocalisedSessionObj(
					session, "langs", lang);
			if (langs == null) {
				langs = LanguageDB.getManager(token).getAll();
				session.setAttribute("langs", langs);
			}
		}
		return modeSelect(mapping, form, request, response);
	}
	public ActionForward modeList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		TrnHarvestLocationDB thldb = TrnHarvestLocationDB.getManager(token);
		List l = thldb.getList();
		Utils.setBreadCrumbs(request,"bc.te.list");
		request.setAttribute("harvesters", l);
		return mapping.findForward("list");
	}
	public ActionForward modeSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		TrnHarvestLocationForm thlf = (TrnHarvestLocationForm) form;
		DBWrapper db = DBWrapper.getManager(token);
		TrnHarvestLocation t = new TrnHarvestLocation();
		t.setName(thlf.getName());
		t.setBaseURL(thlf.getBaseURL());
		t.setLang(thlf.getLang());
		t.setId(thlf.getId());
		db.synchronize(t);
		return modeList(mapping, form, request, response);
	}
	public ActionForward modeEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		DBWrapper db = DBWrapper.getManager(token);
		TrnHarvestLocationForm thlf = (TrnHarvestLocationForm) form;
		Utils.setBreadCrumbs(request,"bc.te.edit");
		int id = 0;
		if (request.getParameter("id") != null) {
			id = Integer.parseInt(request.getParameter("id"));
			TrnHarvestLocation thl = (TrnHarvestLocation) db
					.get(new TrnHarvestLocation(id));
			thlf.setId(thl.getId());
			thlf.setName(thl.getName());
			thlf.setLang(thl.getLang());
			thlf.setBaseURL(thl.getBaseURL());
		}
		return mapping.getInputForward();
	}
	public ActionForward modeSelect(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (request.getParameter("delete") != null)
			return modeDelete(mapping, form, request, response);
		if (request.getParameter("add") != null)
			return mapping.getInputForward();
		if (request.getParameter("save") != null)
			return modeSave(mapping, form, request, response);
		if (request.getParameter("edit") != null)
			return modeEdit(mapping, form, request, response);
		if (request.getParameter("publish") != null)
			return modePublish(mapping, form, request, response);
		if (request.getParameter("harvest") != null)
			return modeHarvest(mapping, form, request, response);
		return modeList(mapping, form, request, response);
	}
	public ActionForward modeHarvest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DBWrapper db = DBWrapper.getManager(token);
		String plang = request.getParameter("plang");
		int id = Integer.parseInt(request.getParameter("id"));
		TrnHarvestLocation thl = (TrnHarvestLocation) db
				.get(new TrnHarvestLocation(id));
		JAXBContext jc = JAXBContext
				.newInstance("ro.ro_gateway.schemas.lpdte_013");
		TranslatorDBAccessor tdb = TranslatorDBAccessor.getManager(token);
		Unmarshaller m = jc.createUnmarshaller();
		Translations trns_in;
		//grab the translations via HTTP:
		String fromdate = "all";
		if (thl.getPerformed() != null)
			fromdate = sdt.format(thl.getPerformed());
//		String xml = LPDRelay.getHTTP();
		try {
			trns_in = (Translations) m.unmarshal(new URL(thl.getBaseURL()
					+ "/translator/exchange.do?publish&fromdate=" + fromdate
					+ "&plang=" + plang));
//			xml = null;
			if (trns_in.getTrn() != null) {
				Iterator i = trns_in.getTrn().iterator();
				while (i.hasNext()) {
					Trn element = (Trn) i.next();
					TransItem ti = new TransItem();
					ti.setSource(trns_in.getSrc());
					ti.setLabel(element.getName());
					ti.setLang(element.getLanguage());
					ti.setModule(element.getModule());
					ti.setText(element.getValue());
					ti.setUpdated(new Timestamp(element.getUpdated()
							.getTimeInMillis()));
					if (tdb.getByModuleLabelAndLang(ti.getModule(), ti
							.getLabel(), ti.getLang()) == null)
						tdb.insert(ti);
					else
						tdb.updateByModuleLabelAndLang(ti);
				}
				request.setAttribute("translations", trns_in.getTrn());
			}
		} catch (Exception e) {
			Utils.setBreadCrumbs(request,"bc.te.result");
			return mapping.findForward("sitedown");
		}
		db.synchronize(new TrnHarvestLocation(new Timestamp(System
				.currentTimeMillis()),id));
		Utils.setBreadCrumbs(request,"bc.te.result");
		return mapping.findForward("result");
	}
	public ActionForward modeDelete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DBWrapper db = DBWrapper.getManager(token);
		String[] delharvesters = request.getParameterValues("delharvesters");
		if (delharvesters != null)
			for (int i = 0; i < delharvesters.length; i++)
				db.delete(new TrnHarvestLocation(Integer
						.parseInt(delharvesters[i])));
		return modeList(mapping, form, request, response);
	}
	/**
	 * this method will output the translation tags for the default language
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return @throws
	 *         Exception
	 */
	public ActionForward modePublish(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String fromstringdate = request.getParameter("fromdate");
		TranslatorDBAccessor tdb = TranslatorDBAccessor.getManager(token);
		Date fromdate;
		if ("all".equals(fromstringdate))
			fromdate = new Date(0);
		else
			fromdate = sdt.parse(fromstringdate);
		String plang = request.getParameter("plang");
		List trns_in = tdb.getByDateAndLang(new Timestamp(fromdate
				.getTime()), plang);
		response.setContentType("text/xml");
		ObjectFactory objFactory = new ObjectFactory();
		Translations trns_out = objFactory.createTranslations();
		trns_out.setSrc(request.getServerName() + request.getContextPath());
		JAXBContext jc = JAXBContext
				.newInstance("ro.ro_gateway.schemas.lpdte_013");
		Iterator i = trns_in.iterator();
		while (i.hasNext()) {
			TransItem item_in = (TransItem) i.next();
			Trn item_out = objFactory.createTrn();
			item_out.setLanguage(item_in.getLang());
			item_out.setModule(item_in.getModule());
			item_out.setName(item_in.getLabel());
			Calendar cal_u = Calendar.getInstance();
			cal_u.setTime(item_in.getUpdated());
			item_out.setUpdated(cal_u);
			if (item_in.getText() == null)
				item_in.setText("");
			item_out.setValue(item_in.getText());
			trns_out.getTrn().add(item_out);
		}
		Marshaller m = jc.createMarshaller();
		m.marshal(trns_out, response.getOutputStream());
		return null;
	}
}
